package com.tanhua.server.service;

import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.VideoCommentApi;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.VideoComment;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class VideoCommentService {

    @DubboReference
    private VideoCommentApi videoCommentApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 点赞
     * @param videoId
     */
    public void likeComment(String videoId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = videoCommentApi.hasComment(videoId, UserHolder.getUserId(), CommentType.LIKE);
        //2、如果已经点赞，抛出异常
        if (hasComment) {
          throw new BusinessException(ErrorResult.likeError());
        }
        //3、调用API保存数据到Mongodb
        VideoComment videoComment = new VideoComment();
        videoComment.setPublishId(new ObjectId(videoId));
        videoComment.setCommentType(CommentType.LIKE.getType());
        videoComment.setUserId(UserHolder.getUserId());
        videoComment.setCreated(System.currentTimeMillis());
        videoCommentApi.save(videoComment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + videoId;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
    }
    /**
     * 删除点赞
     * @param videoId
     */
    public void unlikeComment(String videoId) {
         //1、调用API查询用户是否已点赞
        Boolean hasComment = videoCommentApi.hasComment(videoId, UserHolder.getUserId(), CommentType.LIKE);
        //2、如果未点赞，抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3、调用API，删除数据，返回点赞数量
        VideoComment videoComment = new VideoComment();
        videoComment.setPublishId(new ObjectId(videoId));
        videoComment.setCommentType(CommentType.LIKE.getType());
        videoComment.setUserId(UserHolder.getUserId());
        videoCommentApi.delete(videoComment);
        //4、拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + videoId;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY+ UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
    }

}
